package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-08-30
 * Time: 15:59
 */
public class UdpEchoServer {
    private DatagramSocket  socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        //通过死循环来不停的处理客户端的请求
        while(true) {
            //1.读取客户端的请求、
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //上述的得到的数据是二进制数据，若需要打印之类的操作，需要转换为成字符串才好处理。
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());

            //2.计算请求的响应，由于这里是回显服务器，响应就是请求。
            String response = process(request);

            //3.将回应返回到客户端。
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length
            ,requestPacket.getSocketAddress());
            socket.send(responsePacket);

            //4.打印日志.
            System.out.printf("[%s:%d] request = %s response = %s\n",requestPacket.getAddress(),requestPacket.getPort(),
                    request,response);
        }


    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();
    }

}
